var Router = require('express').Router;
var proxy = require("express-http-proxy");
var vhost = require("vhost");
var settings = require("../config/settings");

/**
 *
 * 描述：代理web端
 *
 * HISTORY
 * ****************************************************************************
 *  ID   DATE           			         PERSON          REASON
 *  1    2015年9月10日 上午11:53:38      Ghold          Create
 * ****************************************************************************
 */
module.exports = function() {
    var router = new Router();

    router.all("/", vhost(settings.web_host, proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/web" + require('url').parse(req.url).path;
        }
    })));

    router.all("/", vhost(settings.home_server, proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/web" + require('url').parse(req.url).path;
        }
    })));

    router.all("/", vhost(settings.wechat_host, proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/wechat" + require('url').parse(req.url).path;
        }
    })));

    router.all("/", vhost(settings.cms_host, proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/cms" + require('url').parse(req.url).path;
        }
    })));

    router.use('/web', proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/web" + require('url').parse(req.url).path;
        }
    }));

    router.use('/wechat', proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/wechat" + require('url').parse(req.url).path;
        }
    }));

    router.use('/cms', proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/cms" + require('url').parse(req.url).path;
        }
    }));

    router.use('/view', proxy(settings.proxy_host + settings.proxy_port, {
        forwardPath: function(req, res) {
            return "/cms/view" + require('url').parse(req.url).path;
        }
    }));

    router.use('/.well-known/acme-challenge', proxy(settings.proxy_host, {
        forwardPath: function(req, res) {
            return "/.well-known/acme-challenge" + require('url').parse(req.url).path;
        }
    }));

    // router.use('/web', proxy(settings.home_server, {
    //     forwardPath: function(req, res) {
    //         return "/web" + require('url').parse(req.url).path;
    //     }
    // }));

    router.unless = require('express-unless');

    return router;
};
